package com.sita.bike.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.colintmiller.simplenosql.NoSQL;
import com.colintmiller.simplenosql.NoSQLEntity;
import com.easemob.chat.EMChatManager;
import com.sita.bike.R;
import com.sita.bike.beans.PersonBean;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Account;
import com.sita.bike.rest.model.Location;
import com.sita.bike.rest.model.LoginRequest;
import com.sita.bike.rest.model.RestResponse;
import com.sita.bike.rest.model.RtResource;
import com.sita.bike.rest.model.ThirdPartyRegisterRequestParams;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.support.LocationController;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.LocalStorage;
import com.sita.bike.utils.PersistUtils;
import com.sita.bike.utils.PhoneUtils;
import com.sita.bike.utils.RetrofitUtils;
import com.sita.bike.utils.ValidateUtils;
import com.sita.friend.FriendHelper;
import com.sita.friend.db.DBManager;
import com.sita.friend.ui.activity.MainActivity;
import com.sita.tboard.hitchhike.bean.Driver;
import com.sita.tboard.hitchhike.listeners.OnGetDriverInfoListener;
import com.sita.tboard.hitchhike.helper.HitchhikeNetworkHelper;
import com.sita.tboard.global.AccountManager;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.weixin.controller.UMWXHandler;

import java.util.Date;
import java.util.Map;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Class LoginActivity is for
 *
 * @author xiaodong on 15/3/2.
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = LoginActivity.class.getSimpleName();
    //    private Toolbar mToolbar;
    private EditText mMobileEdit;
    private EditText mPasswordEdit;
    private Button mLoginBtn;
    private TextView mRegtv;

    private PersonBean personBean;
    private boolean newPerson;
    private Button btn_Qq;
    private Button btn_Weixin;
    private UMSocialService mSocialService;
    private String gender;
    private String screenName;
    private String headerImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        if (null == personBean) {
            personBean = PersistUtils.findPersonBean();
        }
        initViews();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initViews() {
        mLoginBtn = (Button) findViewById(R.id.login_button);
        mLoginBtn.setOnClickListener(this);
        mRegtv = (TextView) findViewById(R.id.register_text);
        mRegtv.setOnClickListener(this);
        btn_Qq = (Button) findViewById(R.id.btn_qq);
        btn_Weixin = (Button) findViewById(R.id.btn_weixin);
        btn_Weixin.setOnClickListener(this);
        btn_Qq.setOnClickListener(this);

        mMobileEdit = (EditText) findViewById(R.id.login_et_mobile);
        mPasswordEdit = (EditText) findViewById(R.id.login_et_pwd);
        mMobileEdit.setError(null);
        mPasswordEdit.setError(null);
        mMobileEdit.requestFocus();
        if (null != personBean.person) {
            mMobileEdit.setText(personBean.person.getMobile());
        }
    }

    private void attemptLogin() {
        String mobile = mMobileEdit.getText().toString();
        String password = mPasswordEdit.getText().toString();
        if (mobile.length() > 11) {
            mobile = mobile.substring(0, 11);
            mMobileEdit.setText(mobile);
        }
        if (!ValidateUtils.checkMobile(mobile)) {
            mMobileEdit.setError(getString(R.string.error_invalid_mobile));
            mMobileEdit.requestFocus();
            return;
        }
        if (!ValidateUtils.checkPassword(password)) {
            mPasswordEdit.setError(getString(R.string.error_invalid_password));
            mPasswordEdit.requestFocus();
            return;
        }

        if (personBean.person.getMobile() == null) {
            newPerson = true;
        }

        personBean.person.setMobile(mobile);
        personBean.person.setName(mobile);
        personBean.pushDeviceId = PhoneUtils.getDeviceId();
        personBean.pushToken = PhoneUtils.getDeviceToken();
        personBean.password = password;

        final MaterialDialog dialog = new MaterialDialog.Builder(this).title(R.string.user_login).content(R.string.logining)
                .progress(true, 15000)
                .build();
        dialog.show();

        doLogin(dialog);
    }

    public void initData() {
        mSocialService = UMServiceFactory.getUMSocialService("com.umeng.login");
        mSocialService.getConfig().setPlatforms(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.SINA);
        //参数1为当前Activity， 参数2为在QQ互联申请的APP ID，参数3为在QQ互联申请的APP kEY.
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(LoginActivity.this, "1105003410",
                "Z5QAdaQVUcIQ5M3P");
        qqSsoHandler.addToSocialSDK();

        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(LoginActivity.this,
                "wx39756127c1fb8165", "8c22c67a43079ca0d2fa471b51b0bdb8");
        wxHandler.setRefreshTokenAvailable(false);
        wxHandler.addToSocialSDK();

        //添加新浪平台
        mSocialService.getConfig().setSsoHandler(new SinaSsoHandler());

    }

    private void doLogin(final MaterialDialog dialog) {
        LoginRequest req = new LoginRequest();
        req.mMobile = personBean.person.getMobile();
        req.mPassword = personBean.password;

        RestClient.getRestService().login(req, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200) {
                    if (restResponse.mErrorCode.equals("0") && restResponse.mData != null) {
                        String s = RestClient.getGson().toJson(restResponse.mData);
                        Account account = RestClient.getGson().fromJson(s, Account.class);
                        if (account != null) {
                            personBean.person.setAvatarUrl(account.mAvatar);
                            personBean.person.setMobile(account.mMobile);
                            personBean.person.setName(account.mNickName);
                            personBean.credential.setXmppUser(account.mImId);
                            personBean.credential.setXmppPass(account.mImPwd);
                            personBean.credential.setLastLoginTime(new Date());

                            // TODO
                            if (personBean.credential.getToken() == null) {
                                personBean.credential.setToken("token");
                            }

                            // TODO get account information (head, name)
                            loginSuccess(account, dialog);
                        } else {
                            loginFailed(dialog);
                        }

                    } else {
                        loginFailed(dialog);
                    }
                }

            }

            @Override
            public void failure(RetrofitError error) {
                dialog.dismiss();
                RetrofitUtils.displayError(LoginActivity.this, error);
            }
        });
    }

    private void loginFailed(MaterialDialog dialog) {
        Toast.makeText(LoginActivity.this, "登录失败, 请重试！", Toast.LENGTH_LONG).show();
        dialog.dismiss();
    }

    private void loginSuccess(Account account, MaterialDialog dialog) {
        AccountManager.getInstance().setAccount(account);
        String accountId = LocalStorage.getAccountId();

        boolean sync = false;
        if (TextUtils.isEmpty(accountId) || !accountId.equals(account.mAccountId)) {
            deleteStore();
            FriendHelper.getInstance().getContactList().clear();

            // save a stub account for reference
            LocalStorage.setAccountId(account.mAccountId);

            sync = true;
        }
        PersistUtils.savePersonCredential(personBean);
        PersistUtils.saveTrendMember(account);

        HitchhikeNetworkHelper.INSTANCE.getDriver(new OnGetDriverInfoListener() {
            @Override
            public void onSuccess(Driver driverInfo) {
                
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });

        if (sync){
            FriendHelper.getInstance().syncFromServer();
        }
        NoSQLEntity<Account> entity = new NoSQLEntity<Account>(Constants.ACCOUNT_BUCKET, account.mAccountId, account);
        NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class).save(entity);

        if (dialog != null && !dialog.isCancelled()){
            dialog.dismiss();
        }
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        LoginActivity.this.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_button: {
                attemptLogin();
                break;
            }
            case R.id.register_text: {
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            }
            case R.id.btn_qq:
                qqLogin();
                break;
            case R.id.btn_weixin:
                weixinLogin();
                break;
        }
    }

    public void qqLogin() {
        mSocialService.doOauthVerify(LoginActivity.this, SHARE_MEDIA.QQ, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                Log.d(TAG, "获取平台数据开始...");
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
//                Toast.makeText(LoginActivity.this, "授权错误", Toast.LENGTH_SHORT).show();
                Log.i("tagsddd", "" + e);
            }

            @Override
            public void onComplete(final Bundle value, final SHARE_MEDIA platform) {
//                Toast.makeText(LoginActivity.this, "授权完成", Toast.LENGTH_SHORT).show();
                String uid = value.getString("uid");
                //获取相关授权信息
                mSocialService.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, new SocializeListeners.UMDataListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete(final int status, Map<String, Object> info) {
                        if (status == 200 && info != null) {
                            thirdPartyQqRegisterAndLogin(value, platform, info);
                        } else {
                            Toast.makeText(LoginActivity.this, "发生错误: " + status, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void weixinLogin() {
        mSocialService.doOauthVerify(LoginActivity.this, SHARE_MEDIA.WEIXIN, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(final Bundle value, final SHARE_MEDIA platform) {
                String uid = value.getString("uid");
                if (uid != null) {
                    Log.d(TAG, "授权完成");
                }
                //获取相关授权信息
                mSocialService.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, new SocializeListeners.UMDataListener() {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        if (status == 200 && info != null) {
                            thirdPartyWeixinRegisterAndLogin(value, platform, info);
                        } else {
                            Log.d("TestData", "发生错误：" + status);
                        }
                    }
                });
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void doLogin3rd(final ThirdPartyRegisterRequestParams params) {
        final MaterialDialog uploadDialog = new MaterialDialog.
                Builder(this).
                content(R.string.logining_wait).
                progress(true, 10000).
                build();
        uploadDialog.show();

        RestClient.getRestNormalService().thirdPartyLogin(params, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200) {
                    if (restResponse.mErrorCode.equals("0") && restResponse.mData != null) {
                        String s = RestClient.getGson().toJson(restResponse.mData);
                        Account account = RestClient.getGson().fromJson(s, Account.class);
                        personBean.person.setAvatarUrl(account.mAvatar);
                        personBean.person.setName(account.mNickName);
                        personBean.person.setAddress(account.mSignature);
                        personBean.person.setEmail(account.mEmail);
                        personBean.person.setMobile(account.mMobile);
                        personBean.credential.setToken(params.mAccessToken);
                        personBean.credential.setXmppUser(account.mImId);
                        personBean.credential.setXmppPass(account.mImPwd);
                        personBean.credential.setLastLoginTime(new Date());
                        personBean.credential.setPersonId(Long.valueOf(account.mAccountId));
                        personBean.password = "pwd";
                        personBean.pushDeviceId = "pushDeviceId";
                        personBean.pushToken = "pushToken";

                        uploadDialog.dismiss();

                        loginSuccess(account, uploadDialog);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                uploadDialog.dismiss();
            }
        });
    }

    public void thirdPartyWeixinRegisterAndLogin(final Bundle value, final SHARE_MEDIA platform, final Map<String, Object> info) {
        ThirdPartyRegisterRequestParams params = new ThirdPartyRegisterRequestParams();
        params.mProvider = "WECHAT";
        params.mGender = info.get("sex").toString();
        params.mNickname = info.get("nickname").toString();
        params.mExpire = 12345;
        params.mAvatar = info.get("headimgurl").toString();
        params.mAccount = value.getString("uid");
        params.mAccessToken = value.getString("access_token");
        Location loc = new Location();
        AMapLocation location = LocationController.getLastKnownLocation();
        if (location != null) {
            loc.latitude = String.valueOf(location.getLatitude());
            loc.longitude = String.valueOf(location.getLongitude());
        }
        params.mLocation = loc;
        doLogin3rd(params);
    }

    private void thirdPartyQqRegisterAndLogin(final Bundle value, final SHARE_MEDIA platform, final Map<String, Object> info) {
        ThirdPartyRegisterRequestParams params = new ThirdPartyRegisterRequestParams();
        params.mProvider = platform.toString();
        params.mGender = info.get("gender").toString();
        params.mAccessToken = value.getString("access_token");
        params.mAccount = value.getString("uid");
        params.mAvatar = info.get("profile_image_url").toString();
        params.mExpire = 12345;
        params.mNickname = info.get("screen_name").toString();
        Location loc = new Location();
        AMapLocation location = LocationController.getLastKnownLocation();
        if (location != null) {
            loc.latitude = String.valueOf(location.getLatitude());
            loc.longitude = String.valueOf(location.getLongitude());
        }
        params.mLocation = loc;

        Log.i(TAG, params.toString());
        doLogin3rd(params);
    }

    private void deleteStore(){
        PersistUtils.clearDatabase();
        AccountUtils.resetAccountCacheInfo();
        LocalStorage.clearLocalStorage();
        EMChatManager.getInstance().deleteAllConversation();

        DBManager.getInstance().deleteAllContacts();
        DBManager.getInstance().deleteAllMessages();

        NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class)
                .bucketId(Constants.ACCOUNT_BUCKET).delete();

        NoSQL.with(GlobalContext.getGlobalContext()).using(RtResource.class)
                .bucketId(Constants.RT_RESOURCE_BUCKET).delete();

        NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class)
                .bucketId(Constants.RT_BLACKLIST_BUCKET).delete();
    }
}


